package ru.amse.jsynchro.net.stream;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class LimitedOutputStream extends FilterOutputStream {
    protected final int BUFFER_SIZE = 1024;
    protected byte[] buffer;
    protected int bufferPos;
    protected long limit;
    
    protected LimitedOutputStream(OutputStream out) {
        super(out);
        buffer = new byte[BUFFER_SIZE];
    }
    
    public LimitedOutputStream(OutputStream out, long limit) {
        this(out);
        this.limit = limit;
    }
    
    public void write(int b) throws IOException {
        limit--;
      if (limit >= 0) {
          buffer[bufferPos++] = (byte) b;
          if (bufferPos == BUFFER_SIZE) {
              out.write(buffer);
              bufferPos = 0;
          }
      }
      if ((limit == 0) && (bufferPos != 0)) {
          out.write(buffer, 0, bufferPos);
      }
    }
}
